package com.onlyoffice.demo.ai.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.chat.memory.repository.jdbc.JdbcChatMemoryRepository;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ResourceLoader;

/**
 * AI聊天客户端配置
 *
 * @author ZWX
 * @date 2025-07-16
 */
@SpringBootConfiguration
public class ChatClientConfig {

    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 配置OpenAI聊天客户端
     *
     * @param chatModel OpenAI聊天模型
     * @return OpenAI聊天客户端
     */
    @Bean
    public ChatClient openAiChatClient(OpenAiChatModel chatModel, ChatMemory chatMemory) {
        return ChatClient
                // 配置聊天模型
                .builder(chatModel)
                // 配置日志、MySQL聊天记忆
                .defaultAdvisors(new SimpleLoggerAdvisor(), MessageChatMemoryAdvisor.builder(chatMemory).build())
                // 配置系统提示词
                .defaultSystem(resourceLoader.getResource("classpath:prompt/law-ai.txt"))
                .build();
    }

    /**
     * 配置MySQL聊天记忆
     * https://github.com/spring-projects/spring-ai/tree/main/memory/repository/spring-ai-model-chat-memory-repository-jdbc
     * /src/main/resources/org/springframework/ai/chat/memory/repository/jdbc
     *
     * @param chatMemoryRepository JdbcChatMemoryRepository
     * @return MySQL聊天记忆
     */
    @Bean
    public ChatMemory mysqlChatMemory(JdbcChatMemoryRepository chatMemoryRepository) {
        return MessageWindowChatMemory.builder()
                .chatMemoryRepository(chatMemoryRepository)
                .maxMessages(20)
                .build();
    }
}
